'use client';

import React, { useContext } from 'react';
import { TimeContext, SIMULATION_START_TIME, SIMULATION_END_TIME } from '@/context/TimeContext';
import { Slider } from "@/app/components/ui/slider";
import { Play, Pause } from 'lucide-react';
import { formatUTCDate } from '@/lib/utils';

const totalSlots = (SIMULATION_END_TIME.getTime() - SIMULATION_START_TIME.getTime()) / (30 * 60 * 1000);

export default function TimeController() {
  const context = useContext(TimeContext);

  if (!context) {
    return <div>Loading Time Controller...</div>;
  }

  const { currentTime, setCurrentTime, isPlaying, setIsPlaying } = context;

  const sliderValue = (currentTime.getTime() - SIMULATION_START_TIME.getTime()) / (30 * 60 * 1000);

  const handleSliderChange = (value: number[]) => {
    const newTime = new Date(SIMULATION_START_TIME.getTime() + value[0] * 30 * 60 * 1000);
    setCurrentTime(newTime);
  };

  // const formattedTime = currentTime.toLocaleString('zh-CN', {
  //   timeZone: 'Asia/Shanghai', // 明确指定显示为东八区时间
  //   year: 'numeric',
  //   month: '2-digit',
  //   day: '2-digit',
  //   hour: '2-digit',
  //   minute: '2-digit',
  //   second: '2-digit',
  //   hour12: false
  // }).replace(/\//g, '-');

  const formattedTime = formatUTCDate(currentTime);

  return (
    // 添加一个带背景和内边距的容器，让它更明显
    <div className="flex items-center gap-4 px-4 py-2 bg-gray-800/70 rounded-lg border border-gray-700 backdrop-blur-sm">
      {/* 播放/暂停按钮 */}
      <button 
        onClick={() => setIsPlaying(!isPlaying)} 
        className="p-2 rounded-full hover:bg-gray-700 transition-colors flex-shrink-0"
        aria-label={isPlaying ? '暂停' : '播放'}
      >
        {isPlaying ? <Pause size={20} className="text-white" /> : <Play size={20} className="text-white" />}
      </button>

      {/* 时间显示 */}
      <div className="text-sm font-mono text-white whitespace-nowrap">
        {formattedTime}
      </div>

      {/* 时间滑块 - 增加最小宽度确保可见 */}
      <div className="w-64 min-w-[16rem]">
        <Slider
          value={[sliderValue]}
          max={totalSlots}
          step={1}
          onValueChange={handleSliderChange}
          className="w-full"
        />
      </div>
    </div>
  );
}